const WXAPI = require('apifm-wxapi')
const wxbarcode = require('wxbarcode')
const AUTH = require('../../utils/auth')
const wxpay = require("../../utils/pay.js");
const util = require('../../utils/util');
const share = require('../../utils/share')
const APP = getApp()
APP.configLoadOK = () => {

}
Page({
  data: {
    apiOk: false,
    isLogined: true,
    currentTab:0,
    page:1,
    pageSize:10,
    currentOrderList:[],
    allOrderList:[],
    goodsMap:{},
    hasMore:true
  },
  onLoad: function (options) {
    
  },
  onShow: function () {
    AUTH.checkHasLogined().then(isLogined => {
      this.setData({
        isLogined
      })
      if (isLogined) {
        this.currentOrderList();
        this.doneShow();
       this. getUserInfo()
      }
    })
  },

  async currentOrderList() {
    wx.showLoading({
      title: '',
    })
    const res = await WXAPI.orderList({
      type: 0,
      statusBatch: '1,2'
    })
    wx.hideLoading()
    if (res.code === 0) {
      this.setData({
        currentOrderList: res.data.orderList,
        logisticsMap: res.data.logisticsMap,
        goodsMap: res.data.goodsMap,
        apiOk: true
      })

      // wxbarcode.qrcode('qrcode_0', res.data.orderList[0].orderNumber, 400, 400);
    } else {
      this.setData({
        currentOrderList: null,
        apiOk: true
      })
    }
  },
  async bindChange(e) {
    const index = e.detail.current
    const hxNumber = this.data.currentOrderList[index].orderNumber
    if (!hxNumber) {
      return
    }    
    wxbarcode.qrcode('qrcode_' + index, hxNumber, 400, 400);
  },

  async getDelivery(order){
    return  await WXAPI.getOrderDelivery(order.id,order.groupId)
  },

  cancelOrderTap: function(e) {
    const that = this;
    const orderId = e.currentTarget.dataset.id;
    wx.showModal({
      title: '确定要取消该订单吗？',
      content: '',
      success: function(res) {
        if (res.confirm) {
          WXAPI.orderClose(wx.getStorageSync('token'), orderId).then(function(res) {
            if (res.code == 0) {
              that.refreshOrder(orderId);
              // that.onShow();
            }
          })
        }
      }
    })
  },
  async refreshOrder(orderId){
    const res = await WXAPI.orderDetail("",orderId)
    if(res.code===0){
      let  order = res.data.orderInfo
      let that= this
      this.data.allOrderList.forEach((v,index)=>{
        if(v.id === order.id){
          that.data.currentOrderList[index] = order
          this.setData({
            currentOrderList:that.data.orderList
          })
        }
      })
    }
  },
  toPayTap: function(e) {
    // 防止连续点击--开始
    if (this.data.payButtonClicked) {
      wx.showToast({
        title: '休息一下~',
        icon: 'none'
      })
      return
    }
    this.data.payButtonClicked = true
    setTimeout(() => {
      this.data.payButtonClicked = false
    }, 3000)  // 可自行修改时间间隔（目前是3秒内只能点击一次支付按钮）
    // 防止连续点击--结束
    const that = this;
    const orderId = e.currentTarget.dataset.id;
    let money = e.currentTarget.dataset.money;
    const needScore = e.currentTarget.dataset.score;
    WXAPI.userAmount(wx.getStorageSync('token')).then(function(res) {
      if (res.code == 0) {
        // 增加提示框
        if (res.data.score < needScore) {
          wx.showToast({
            title: '您的积分不足，无法支付',
            icon: 'none'
          })
          return;
        }
        let _msg = '订单金额: ' + money +' 元'
        if (res.data.balance > 0) {
          _msg += ',可用余额为 ' + res.data.balance +' 元'
          if (money - res.data.balance > 0) {
            _msg += ',仍需微信支付 ' + util.sub(money ,res.data.balance) + ' 元'
          }
        }
        if (needScore > 0) {
          _msg += ',并扣除 ' + needScore + ' 积分'
        }
        money = money - res.data.balance
        wx.showModal({
          title: '请确认支付',
          content: _msg,
          confirmText: "确认支付",
          cancelText: "取消支付",
          success: function (res) {
            if (res.confirm) {
              that._toPayTap(orderId, money)
            } else {
              console.log('用户点击取消支付')
            }
          }
        });
      } else {
        wx.showModal({
          title: '错误',
          content: '无法获取用户资金信息',
          showCancel: false
        })
      }
    })
  },
  _toPayTap: function (orderId, money){
    const _this = this
    if (money <= 0) {
      // 直接使用余额支付
      WXAPI.orderPay(wx.getStorageSync('token'), orderId).then(function (res) {
        console.log(res.code,'code');
        if(res.code !== 0){
          wx.showModal({
            content: res.msg,
            showCancel: false
          })
        }
        _this.onShow();
      })
    } else {
      wxpay.wxpay('order', money, orderId, "/pages/all-orders/index");
    }
    _this.onShow();
  },
  orderDetail(e){
    const id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: '/pages/order-details/index?id='+id,
    })
  },
  goGroupDetail(e){
    const id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: '/pages/group-detail/index?id='+id,
    })
  },
  
  // onShow: function() {
  //   AUTH.checkHasLogined().then(isLogined => {
  //     if (isLogined) {
  //       this.doneShow();
  //     } else {
  //       wx.showModal({
  //         content: '登陆后才能访问',
  //         showCancel: false,
  //         success: () => {
  //           wx.navigateBack()
  //         }
  //       })
  //     }
  //   })
  // },
  async doneShow() {
    wx.showLoading({
      title: '',
    })
    const res = await WXAPI.orderList({
      page:this.data.page,
      pageSize:this.data.pageSize,

    })
    wx.hideLoading()
    if (res.code === 0) {
      const orderList = res.data.orderList
      orderList.forEach(ele => {
        if(ele.status === 0){
          ele.countDown = this.caclulateCountDown(ele.expireTimeStamp)
        }

      })
      if(this.data.page === 1){
        this.setData({
          allOrderList: res.data.orderList,
          logisticsMap: res.data.logisticsMap,
          goodsMap: res.data.goodsMap,
          apiOk: true
        });
      }else{
        this.setData({
          allOrderList: this.data.allOrderList.concat( res.data.orderList),
          logisticsMap: {...res.data.logisticsMap,...this.data.logisticsMap},
          goodsMap: {...res.data.goodsMap,...this.data.goodsMap},
          apiOk: true
        });
      }

    }else{
      this.setData({hasMore:false
      })
    }
  },
  toIndexPage: function() {
    wx.switchTab({
      url: "/pages/index/index"
    });
  },
  // 删除订单
  deleteOrder: function(e){
    const that = this
    const id = e.currentTarget.dataset.id;

    wx.showModal({
      title: '提示',
      content: '确定要删除该订单吗？',
      success: function (res) {
        if (res.confirm) {

          WXAPI.orderDelete(wx.getStorageSync('token'), id).then(function (res) {
            if (res.code === 0) {
              that.data.allOrderList.forEach((order,index)=>{
                if(order.id === id)
                  that.data.allOrderList.splice(index,1);
                that.setData({allOrderList:that.data.allOrderList})
              })
            }

          })
        } else {
          console.log('用户点击取消')
        }
      }
    })
  },
 async  onTabChange(e){
    const currentTab = e.detail.index
    this.setData({currentTab})
    if (currentTab === 0){
     await this.currentOrderList()
    }else {
     await this.doneShow()
    }
  },
  onReachBottom(){
    if(this.data.currentTab ===0 || !this.data.hasMore){
      return ;
    }
    this.data.page ++
    this.doneShow()
  },
  caclulateCountDown(expireTime){

    const now = new Date()

    return expireTime - now.getTime() ;

  },
  async callShop(e) {
    const shopId = e.currentTarget.dataset.shopid
    const res = await WXAPI.shopSubdetail(shopId)
    if (res.code != 0) {
      wx.showToast({
        title: res.msg,
        icon: 'none'
      })
      return
    }
    wx.makePhoneCall({
      phoneNumber: res.data.linkPhone,
    })
  },
  async getUserInfo(){
    const currentUser =  await AUTH.getCurrentUser()
    this.setData({
      currentUser
    })
  },
  async onShareAppMessage(event){

    const order = event.target.dataset.detail
    const res = await WXAPI.getGroupInfo(order.groupId)

    if (res.code === 0){
      const group = res.data
     return await share.inviteToGroup(group)
    }
  },
  async onPullDownRefresh() {
    if (this.data.currentTab ===1){
      this.setData({page:1,hasMore:true})
      await this.doneShow()
    }
    await  wx.stopPullDownRefresh()
  },
 async refreshDoing(){
  await this.currentOrderList()
  }
})